package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户提交订单
     * @param orderSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrderSubmitDTO orderSubmitDTO) {
        // 判断地址是否为空, 若为空抛出业务异常
        AddressBook addressBook = addressBookMapper.getById(orderSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 检查购物车是否为空, 若为空抛出业务异常
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 向orders表里插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO, orders);

        orders.setOrderTime(LocalDateTime.now());

        String address = addressBook.getCityName() + addressBook.getDistrictName() +addressBook.getDetail();
        orders.setAddress(address);

        orders.setUserId(userId);

        orders.setConsignee(addressBook.getConsignee());

        orders.setStatus(Orders.PENDING_PAYMENT);

        orders.setPayStatus(Orders.UN_PAID);

        orders.setPhone(addressBook.getPhone());

        orders.setUserName(addressBook.getConsignee());

        String number = System.currentTimeMillis() + String.valueOf(userId);
        orders.setNumber(number);

        ordersMapper.insert(orders);

        // 向order_detail表里插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        // 批量插入order_detail表
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空购物车
        shoppingCartMapper.deleteAll(shoppingCart);
        // 组装OrderSubmitVO对象并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderNumber(number)
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付成功
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 修改订单表状态
        Orders orders = Orders.builder()
                .userId(userId)
                .number(ordersPaymentDTO.getOrderNumber())
                .status(Orders.TO_BE_CONFIRMED)
                .checkoutTime(LocalDateTime.now())
                .payMethod(ordersPaymentDTO.getPayMethod())
                .payStatus(Orders.PAID)
                .build();

        ordersMapper.updateOrders(orders);
        // 组装vo对象返回
        OrderPaymentVO orderPaymentVO = OrderPaymentVO.builder()
                .nonceStr("paySuccessfully")
                .packageStr("paySuccessfully")
                .paySign("paySuccessfully")
                .timeStamp(String.valueOf(System.currentTimeMillis()))
                .signType("directionSign")
                .build();

        // 调用WebSocket来提示来单
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        // 转换成JSON字符串
        String content = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(content);

        return orderPaymentVO;
    }

    /**
     * 用户端订单分页查询
     */
    @Override
    public PageResult pageQuery4User(Integer page, Integer pageSize, Integer status) {
        // 使用PageHelper设置分页
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页查询orders表
        Page<Orders> ordersPage = ordersMapper.pageQuery(ordersPageQueryDTO);
        // 创建OrderVO对象并返回
        List<OrderVO> list = getOrderVOList(ordersPage);

        if (ordersPage != null) {
            return new PageResult(ordersPage.getTotal(), list);
        }
        return null;
    }

    /**
     * 根据订单id查询详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = ordersMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        String orderDishes = getOrderDishesStr(orderDetailList);
        orderVO.setOrderDishes(orderDishes);
        orderVO.setOrderDetailList(orderDetailList);
        // System.out.println("订单菜品信息" + orderVO.getOrderDishes());

        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        // 根据id查询订单信息
        Orders orderDB = ordersMapper.getById(id);

        // 校验订单是否存在
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 校验订单状态, 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orderDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 创建修改订单的新对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderDB, orders);
        // 订单处于待接单状态下取消，需要进行退款
        if (orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        // 更新数据
        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 管理端条件分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery4Admin(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        if(page != null) {
            return new PageResult(page.getTotal(), orderVOList);
        }
        return null;
    }

    /**
     * 各种订单状态数据统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        return ordersMapper.getStatistics();
    }

    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.updateStatus(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !Objects.equals(ordersDB.getStatus(), Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDB, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        ordersMapper.update(orders);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());
        // 用户已支付，需要退款
        if (Objects.equals(ordersDB.getPayStatus(), Orders.PAID)) {
            ordersDB.setPayStatus(Orders.REFUND);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDB, orders);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);

        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);
        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !Objects.equals(ordersDB.getStatus(), Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDB, orders);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        ordersMapper.updateStatus(orders);
    }

    /**
     * 完成订单
     * @param id
     * @throws Exception
     */
    @Override
    public void complete(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);
        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !Objects.equals(ordersDB.getStatus(), Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDB, orders);
        orders.setStatus(Orders.COMPLETED);

        ordersMapper.updateStatus(orders);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 根据id查询订单信息
        Orders ordersDB = ordersMapper.getById(id);

        // 如果订单不存在, 抛出业务异常
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 只有当订单处于待接单的状态才能进行催单
        if (Objects.equals(ordersDB.getStatus(), Orders.TO_BE_CONFIRMED)) {
            Map<String, Object> map = new HashMap<>();
            map.put("type", 2);
            map.put("orderId", id);
            map.put("content", "订单号为：" + ordersDB.getNumber());

            // 转换为JSON字符串
            String content = JSON.toJSONString(map);

            // 调用WebSocket接口进行消息传递
            webSocketServer.sendToAllClient(content);
        }
    }


    /**
     * 将Orders转化为OrderVO
     * @param page
     * @return
     */

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        // 当page不为空时
        if (page != null && page.getTotal() > 0) {
            page.forEach(order -> {
                Long orderId = order.getId();

                // 查询订单详细信息
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                String orderDishes = getOrderDishesStr(orderDetails);
                orderVO.setOrderDishes(orderDishes);
                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);
            });
        }
        return orderVOList;
    }

    /**
     *
     * @param orderDetails
     * @return
     */
    private String getOrderDishesStr(List<OrderDetail> orderDetails) {
        // 将每一条订单菜品信息拼接为字符串(格式：宫保鸡丁*3;)
        List<String> orderDishes = orderDetails.stream().map(orderDetail -> {
            return orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
        }).collect(Collectors.toList());
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishes);
    }
}
